// 引入运行sql的插件和防止sql 注入的插件
const { exec, escape } = require('../db/mysql')

// 借阅证信息列表
const listCard = (role) => {
    let sql =``
    if(role >1){
        sql = `select * from card;`
    }else{
        sql = `select library_card_id,student_name,student_department,student_major,student_phone,student_borrowed_number,student_limit,student_account,student_is_arrears,student_create_time from card where student_is_delete=0;`
    }
    console.log(sql);
    return exec(sql).then(data => {
        // console.log(data)
        return data
    })
}

// 借阅证信息查询
const searchCard = (role,type,input) => {
    input = escape(input)
    let sql = ``
    if(role > 1){
        sql = `select * from card where ${type}=${input};`
    }else{
        if(role >0){
            sql = `select library_card_id,student_name,student_department,student_major,student_phone,student_borrowed_number,student_limit,student_account,student_is_arrears,student_create_time from card where ${type}=${input} and student_is_delete=0;`
        }else{
            sql = `select library_card_id,student_name,student_department,student_major,student_phone,student_borrowed_number,student_limit,student_account,student_is_arrears,student_create_time from card where ${type}=${input};`
        }
    }
    console.log(sql)
    return exec(sql).then(data => {
        console.log(data)
        return data
    })
}

// 新建借书证
const newCard = (name,department,major,phone,limit,account,time) =>{
    const sql = `insert into card (student_name,student_department,student_major,student_phone,student_limit,student_account,student_create_time,student_update_time) values('${name}','${department}','${major}','${phone}',${limit},'${account}','${time}','${time}');`
    console.log(sql);
    return exec(sql).then(data => {
        console.log(data)
        data.errno = 0
        return data
    }).catch(err => {
        err.errno =1
        return err
    })
}

// 修改借书证
const updateCard =(id,type,input) => {
    input = escape(input)
    const sql = `update card set ${type}=${input} where library_card_id=${id};`
    console.log(sql);
    return exec(sql).then(data => {
        // console.log(data)
        data.errno = 0
        return data
    }).catch(err => {
        err.errno = 1
        return err
    })
}

// 删除借阅证
const deleteCard = (id) => {
    id = escape(id)
    const sql =`delete from card where library_card_id=${id};`
    console.log(sql);
    return exec(sql).then(data => {
        console.log(data)
        data.errno = 0
        return data
    }).catch(err => {
        err.errno = 1
        return err
    })
}

module.exports = {
    searchCard,
    listCard,
    newCard,
    updateCard,
    deleteCard
}